//
//  KHHStoryDetailPageViewController.m
//  Travel
//
//  Created by dllo on 15/11/30.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "KHHStoryDetailPageViewController.h"
#import "KHHRecommendModel.h"
#import "KHHStoryDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"
#import "Story.h"
#import "CoreDataManager.h"

@interface KHHStoryDetailPageViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *modelDetailArr;
@property (nonatomic, retain) NSMutableDictionary *userDic;
@property (nonatomic, retain) NSMutableDictionary *detailDic;     //获取当前页文章信息总数据
@property (nonatomic, assign) CGFloat hTitleLable;  //记录第一个分区title的高度
@property (nonatomic, retain) KHHRecommendModel *storyModel;

@property (nonatomic, retain) NSMutableArray *arr_result;
@property (nonatomic, strong) UIButton *btn_like;
@property (nonatomic, retain) CoreDataManager *manager;
@end

@implementation KHHStoryDetailPageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [self selectAllLike];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"leftBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = @"故事详情";
    
    //初始化coredata单例
    self.manager = [CoreDataManager shareInstance];
    
    [self selectAllLike];
    if(self.arr_result.count != 0){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"like2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(likeAction)];
        self.navigationItem.backBarButtonItem.tintColor = [UIColor redColor];
    } else {
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"like1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(likeAction)];
        self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];
    }
    
    //获取数据
    [self getData];
    //创建tableView
    [self createTableView];
    //边沿手势
    [self addScreenEdgePan];
    
    //菊花
    [CXLoadMBProgress loadMBProgress:self.view];

}

#pragma mark-滑动手势1
- (void)addScreenEdgePan
{
    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
    screenEdgePan.edges = UIRectEdgeLeft;
    [self.tableView addGestureRecognizer:screenEdgePan];
    
}
#pragma mark-滑动手势2
-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取数据
- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"%@%@", @"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=",self.spot_id];
   // NSString *url = [NSString stringWithFormat:@"%@%@", @"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=",self.userModel.spot_id];
    [CXNetHandle getUrl:url cookie:nil result:^(id result) {
        
        //移除菊花
        [CXLoadMBProgress removeMBProgress:self.view];
        
        //获取当前页文章信息总数据
        self.detailDic = result[@"data"][@"spot"];
        //获取当前页用户信息数据
        self.userDic = result[@"data"][@"trip"][@"user"];
        
        
        //将文章信息数据转化为对象
        self.modelDetailArr = [KHHRecommendModel transformWithArray:self.detailDic[@"detail_list"]];
        
       // [self.hud removeFromSuperview];
        [self.tableView reloadData];
    }];
    
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 80) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle =    UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    //[[self class]BoolIsNight:self.tableView];
    //注册cell
    [self.tableView registerClass:[KHHStoryDetailTableViewCell class] forCellReuseIdentifier:@"storyDetail"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}


#pragma mark - 自定义按钮触发方法
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //一个分区保存title 一个分区保存图和字的数据
    return 2;
}

#pragma mark - 头部行高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return WIDTH / 3;
    }
    else{
        return 0;
    }
}

#pragma mark - header上面的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
        view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        //头像
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(20, 30, WIDTH / 6, WIDTH / 6)];
        img.layer.masksToBounds = YES;
        img.layer.cornerRadius = img.frame.size.width / 2;
        [view addSubview:img];
        [img sd_setImageWithURL:[NSURL URLWithString:self.userDic[@"avatar_m"]] placeholderImage:[UIImage sd_animatedGIFNamed:@"load"]];
        
        //文字
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(img.frame.origin.x + img.frame.size.width + 10, img.frame.origin.y + 20, WIDTH - 30- img.frame.size.width - 20 - 20, 30)];
        [view addSubview:label];
        label.font = [UIFont fontWithName:@" Menlo-Italic" size:15];
        label.text = self.userDic[@"name"];
        
        //横线label
        UILabel *labelLine = [[UILabel alloc]initWithFrame:CGRectMake(20, img.frame.origin.y + img.frame.size.height + 10, WIDTH - 40, 0.8)];
        labelLine.backgroundColor = [UIColor darkGrayColor];
        [view addSubview:labelLine];
        
        
        //夜间模式
        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"]) {
            view.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
            label.textColor = [UIColor whiteColor];
            labelLine.backgroundColor = [UIColor whiteColor];
            
        }else{
            view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        }
        return view;
        
    } else {
        return nil;
    }
}

#pragma mark - footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return WIDTH / 3 - 50;
    }
}

#pragma mark - tableViewfooterView
//时间view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
        
    } else {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH / 3 - 50)];
        view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        //横线label
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, WIDTH - 60, 1)];
        label.backgroundColor = [UIColor darkGrayColor];
        [view addSubview:label];
        
        //时间图片
        UIImageView *img = [[UIImageView alloc]init];
        img.frame = CGRectMake(30, view.frame.size.height / 2 - 10, 20, 20);
        img.image = [UIImage imageNamed:@"time"];
        [view addSubview:img];
        
        //时间
        UILabel *lable = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:13];
        lable.frame = CGRectMake(img.frame.origin.x + 20 + 10, img.frame.origin.y, 300, img.frame.size.height);
        lable.textColor = [UIColor darkGrayColor];
        
        
        NSString *str = [self.detailDic[@"date_tour"]  substringToIndex:19];
        NSString *str1 = [str stringByReplacingOccurrencesOfString:@"T" withString:@"  "];
        lable.text = str1;
        
        [view addSubview:lable];
        
//        //夜间模式
//        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"]) {
//            view.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
//            label.backgroundColor = [UIColor whiteColor];
//            lable.textColor =[UIColor whiteColor];
//        }else
//        {
//            view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
//        }
        
        return view;
    }
    
}

#pragma mark - 喜欢按钮触发方法
- (void)likeAction
{
    
    [self selectAllLike];
    
    if (self.arr_result.count != 0) {
        NSLog(@"已经收藏");
        //删除
        for (Story *story in self.arr_result) {
            
           [self.manager.managedObjectContext deleteObject:story];
        }
        [self.manager saveContext];
        
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"like1"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏" message:@"取消收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        //[alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // }]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self performSelector:@selector(cancelAlertAction) withObject:alert afterDelay:1.0];
        
    } else {
        //添加
        Story *story = [NSEntityDescription insertNewObjectForEntityForName:@"Story" inManagedObjectContext: self.manager.managedObjectContext];
        
        story.index_cover = self.recommendModel.index_cover;
        story.index_title = self.recommendModel.index_title;
        story.spot_id = self.recommendModel.spot_id;
        story.avatar_m = self.userModel.avatar_m;
        story.name = self.userModel.name;

        [self.manager saveContext];
        
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"like2"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        //[alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //}]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self performSelector:@selector(cancelAlertAction) withObject:alert afterDelay:1.0];
    }
}

//自动取消alert
- (void) cancelAlertAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}


//查询数据库
- (void)selectAllLike
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Story" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"index_title = %@", self.recommendModel.index_title];
    
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
    
    //排序 参数:根据什么排序 yes 升序  / no 降序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"index_title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    }
    [self.arr_result removeAllObjects];
    self.arr_result = [NSMutableArray arrayWithArray:fetchedObjects];
}


#pragma mark - tableViewc cell的count
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
        return self.modelDetailArr.count;
    }
}


#pragma mark - tableView cell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.textLabel.text = self.detailDic[@"text"];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        self.hTitleLable = [[self class]heightWithText:cell.textLabel.text fontSize:17 Width:WIDTH - 40];
        
//        //夜间模式
//        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"]) {
//            cell.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
//            cell.textLabel.textColor = [UIColor whiteColor];
//        }else
//        {
//            cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
//        }
        return cell;
    }
    else
    {
        KHHStoryDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyDetail"];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.detailModel = self.modelDetailArr[indexPath.row ];
        cell.userDic = self.userDic;
        return cell;
    }
}

#pragma mark - tableView行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //0分区 返回文章标题
    if (indexPath.section == 0) {
        return self.hTitleLable ;
    }
    else{
        
        KHHRecommendModel *tempModel = self.modelDetailArr[indexPath.row];
        CGFloat h = [[self class]heightWithText:tempModel.text fontSize:15 Width:WIDTH - 40];

        return (tempModel.photo_height).integerValue * WIDTH / (tempModel.photo_width).integerValue + h + 50;
    }
}

#pragma mark - tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
